<template>
	<div>
        <m-pay :money="orderMoney" :payClick="payClick" :goBack="goBack"></m-pay>
	</div>
</template>

<script>
    import Pay from "../../../real-components/Pay";
    import {mapGetters} from "vuex";
    import getOrderInfo from "../../../api/gw/getOrderInfo";
    import {showLoading, hideLoading} from "../../../utils/loading.js";
    import axios from "axios";
    import * as api from "../../../api/gw/index.js";
    import md5 from "js-md5";
    import {Toast} from "../../../utils/toast";
	export default {
		props: {
			pageType: {
				type: String,
				default: "android"
			}
		},
		data() {
			return {
                orderMoney: 0,
                // orderType: 2,//默认为2，跳到订单列表的待配送状态
                payClick: () => {},
                payParams: null,//翌支付相关的参数
            }
		},
		computed: {
            orderNo() {
                return this.$route.params.orderNo;
            },
            //订单类型，线上订单为2（跳转到待配送），线下订单为1（跳转到全部）,礼品卡为12
            orderType() {
                return this.$route.params.orderType ? this.$route.params.orderType : 2;
            },
            //获取设备类型
            phoneType() {
                let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android
                let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
                return isAndroid ? "Android" : "iOS";
            }

        },
        methods: {
            goBack() {
                // 跳转到待支付页面
                this.$router.replace({"name": "order", query: {orderStatus: 1}});
            },
            //判断是否在可配送时间内
            getTimeRight() {
                console.log("去重新选择时间");
                return new Promise((resolve, reject) => {
                    let url = window.api.trade_host + '/orderDeliveryPool/checkCanToPay/' + this.orderNo;
                    var sessionId = localStorage.getItem('sessionId');
                    let config = {
                        url,
                        method: 'GET',
                        headers: {'sessionId': sessionId},
                    };
                    axios(config).then((res) => {
                        // console.log(res.data.returncode,'返回参数');
                        if(res.data.returnCode === 0){
                            resolve(false);
                        } else if (res.data.returnCode === 1) {
                            resolve(true);
                        }
                    }).catch(err => {
                        reject();
                    });
                });
				
            },
            //定义处理异常错误的加工厂
            defaultErrorResolve() {
                return {
                    //如果没有订单编号，默认跳转到个人中心
                    orderNoError() {
                        this.$router.replace("profile");
                    }
                }
            },
            //初始化支付插件
            initPayPlugin() {
                let SEPayPlugin_Start = () => {
                    //初始化
                    cordova.require('cordova/channel').onCordovaReady.subscribe(function() {
                        //  在安卓 进入后 在注册这个方法的时候 和安卓那边就已经调用这个方法了；
                        //alert("start to pay 2, exec SEPayPlugin  ");
                        cordova.exec(null, null, 'SEPayPlugin',null, []);
                        //CenterCommandPlugin('start');
                        doPay();
                    });
                }
                let doPay = () => { 
                    let data = {
                        pay_no: this.payParams.pay_no,
                        created_ts: this.payParams.created_ts,
                        se_sign: this.payParams.se_sign,
                        use_json: '0',
                        order_money: this.payParams.amount
                    }
                    var pay = "sePay" + JSON.stringify(data);
                    SEPayPlugin(pay,
                        () => {
                            console.log("支付回调", "支付成功");
                            this.$router.replace({"name": "paysuccessfully", params: {orderType: this.orderType}});
                        },
                        () => {
                            console.log("支付失败");
                            Toast({
                                message: '支付失败',
                                type: "fail",
                                duration: 1000
                            });
                    });
                }
                let SEPayPlugin = (params, sucFunc, failFunc, opts, className) => {
                    var params = params || null;
                    var sucFunc = sucFunc || function(){};
                    var failFunc = failFunc || function(){};
                    var opts = opts || {};
                    var className = className || null ;
                    try{
                        console.log("11111111");
                        cordova.exec(sucFunc,failFunc, "SEPayPlugin", "start", [className, params,opts]);
                    }
                    catch(err){
                        alert("如您在app中进行支付，程序调起支付app失败，请点击按钮手动尝试下！")
                    }
                }
                return SEPayPlugin_Start;
            },
            //初始化购买普通的后续
            async init2() {
                //处理异常错误
                if (!this.orderNo) {
                    this.defaultErrorResolve()[orderNoError];
                    return;
                }
                //获取订单信息
                let orderInfo = await getOrderInfo(this.orderNo);
                // console.log("orderInfo", orderInfo);
                //在页面上显示金额
                this.orderMoney = parseFloat(orderInfo.realPay);
                //判断小周的方法，是否需要重新选择下单时间
                this.payClick = async () => {
                    let handleMoneySituationState = await this.handleMoneySituation();
                    // console.log("handleMoneySituationState", handleMoneySituationState)
                    //如果handleMoneySituationState为false，这是一个短路操作，不会重新去选择时间
                    //订单金额为0的不会重新选择时间
                    let timeState = handleMoneySituationState && await this.getTimeRight();
                    // console.log("timeState", timeState);
                    if (!timeState && handleMoneySituationState) {
                        //重新去选择时间
                        this.$router.push({name:'changeOrderTime', query:{orderNo:this.orderNo}});
                        return;
                    }
                    //根据金额判断是否需要调起翌支付的接口
                    //如果handleMoneySituationState为false，代表订单金额为0，直接跳转到支付成功页面
                    //并结束掉操作
                    if (!handleMoneySituationState) {
                        return;
                    }
                    //请求翌支付的参数
                    await this.initPayParams(this.orderNo);
                    //初始化支付插件
                    let SEPayPlugin_Start = this.initPayPlugin();
                    //开始支付
                    SEPayPlugin_Start();
                }
            },
            //初始化翌支付的参数
            initPayParams(params) {
                //一个公共方法
                let getParams = (listData) => {
                    var pay_no = listData.pay_no;  
                    var app_code = listData.app_code;
                    var se_payment_code = listData.se_payment_code;
                    var se_private_key = listData.se_private_key;
                    var created_ts = Date.parse(new Date())/1000;  //
                    var amount = listData.amount;
                    var appStr = app_code + se_payment_code + pay_no + created_ts;
                    var semd5 = md5(appStr) + se_private_key;
                    var se_sign = md5(semd5);
                    return {
                        pay_no,
                        created_ts,
                        se_sign,
                        amount
                    }
                }
                //如果params是一个对象则使用这个参数初始化
                
                if (typeof params === "object") {
                    return new Promise((resolve, reject) => {
                        let p = getParams(params);
                        this.payParams = {
                            pay_no: p.pay_no,
                            created_ts: p.created_ts,
                            se_sign: p.se_sign,
                            amount: p.amount
                        }
                        resolve();
                    });
                }
                //如果是一个字符串，则params是一个订单号，需要去请求数据来初始化参数
                return new Promise((resolve, reject) => {
                    let options = {
                        method: "post",
                        url: window.api.trade_host + api.gwPay,
                        data: {
                            sessionId: localStorage.getItem("sessionId"),
                            "bill_id": params,
                            scenary_id: "3"
                        }
                    }
                    axios(options).then(data => {
                        console.log("请求支付用的参数", data);
                        if (data.status === 200) {

                            //给翌支付所需的参数赋值
                            let result = getParams(data.data.data[0]);
                            this.payParams = {
                                pay_no: result.pay_no,
                                created_ts: result.created_ts,
                                se_sign: result.se_sign,
                                amount: result.amount
                            }
                            resolve(result);
                        } else {
                            reject();
                        }
                    }).catch(err => {
                        console.log(err);
                        reject();
                    });
                });
            },
            //初始化购买礼品卡的后续
            async init3() {
                //处理异常错误
                if (!this.orderNo) {
                    this.defaultErrorResolve()[orderNoError];
                    return;
                }
                //在页面上显示金额
                this.orderMoney = parseFloat(this.orderNo.amount);
                //
                this.payClick = async () => {
                    //请求翌支付的参数
                    await this.initPayParams(this.orderNo);
                    //初始化支付插件
                    let SEPayPlugin_Start = this.initPayPlugin();
                    //开始支付
                    SEPayPlugin_Start();
                }
            },
            //根据不同的金额类型判断不同的处理情况
            handleMoneySituation() {
                return new Promise((resolve, reject) => {
                    if (this.orderMoney > 0) {
                        resolve(true);
                    } else if (this.orderMoney === 0) {
                        resolve(false);
                    }
                })
            }
            
        },
		components: {
			"m-pay": Pay
        },
        created() {
            console.log("1234567", this.$route.params);
            // this.getOrderInfoFromApi();
            // console.log("gwPay", gwPay);
            //orderType
            if (this.orderType === 12) {
                this.init3();
            } else {
                this.init2();
            }
            
        }
	}
</script>

<style>
</style>